import Config from "../config/Config";
import Mysql from "../base/Mysql";
import Redis from "../base/Redis";
import Log4j from "../base/Log4j";
import express = require("express");
export interface ControllerResponse{
    error:boolean;
    data:any;
    reason:string[]
}

export class Controller {
    protected reasons:string[] = [];
    protected db = undefined;
    protected redis;
    protected log4j;


    constructor() {
    }

    protected addErrorReason(reason:string):void{
        this.reasons.push(reason);
    }

    protected hasError():boolean{
        return this.reasons.length > 0;
    }

    /**
     * 构造约定格式的请求响应文本
     * @param any data 返回数据
     * @return ControllerResponse
     */
    protected responseConstruct(data: any): ControllerResponse {
        let responseObj:ControllerResponse = {
            error: true,
            data: data,
            reason: this.reasons
        };
        if(this.reasons.length === 0){
            responseObj.error = false;
        }

        // if(this.redis){
        //     this.redis.close();
        // }
        
        // if(this.db){
        //     this.db.end();
        // }

        return responseObj;
    }

    /**
     * 获取区块链上的账户地址
     * @param keystore 
     * @param pwDerivedKey
     */
    protected getAddress(keystore,pwDerivedKey:Uint8Array){
        keystore.generateNewAddress(pwDerivedKey,2);
        let addresses:string[] = keystore.getAddresses();

        if(addresses.length > 0){
            return '0x'+addresses[0];
        }else{
            return '';
        }
    }

    /**
     * 获取账户对应私钥
     * @param keystore 
     * @param pwDerivedKey
     */
    protected getPrivateKey(accountAddress,keystore,pwDerivedKey:Uint8Array){
        let pk = keystore.exportPrivateKey(accountAddress, pwDerivedKey);
        let privateKey = new Buffer(pk,'hex');

        return privateKey;
    }

    /**
     * 获取账户对应公钥
     * @param keystore 
     * @param pwDerivedKey
     */
    protected getPublicKey(keystore){
        let pk = keystore.getPubKeys();
        let publicKey = new Buffer(pk,'hex');

        return publicKey;
    }


    /**
     * 链接redis
     * @param string name redis名称，用于从config中获取到对应配置
     * @return null
     */
    protected connectRedis(name: string,callback: Function){
        var redisHosts = Config.REDIS_HOSTS;
        var redisConfig = redisHosts[name];
        if(redisConfig){
            var host = redisConfig.HOST;
            var port = redisConfig.PORT;
            var redis = require("redis");
            this.redis = redis.createClient(port, host);
            this.redis.on("error", function(err){  
                console.log("Error: " + err);
            });
            
            this.redis.on("ready", function(err){  
                console.log("ready");
            });
            
            callback(this.redis);
        }
    }

    /**
     * 连接log
     */
    protected log(category: string,data: any){
        this.log4j = new Log4j(category);
        this.log4j.log(data);
    }

    /**
     * 连接mysql
     */
    protected connectMysql(callback: Function){
            if(this.db != undefined){
                callback(this.db);
            }
            let mysql = new Mysql();
            let host,user,password,database,port;
            host = Config.MYSQL_HOSTS.HOST;
            user = Config.MYSQL_HOSTS.USER;
            password = Config.MYSQL_HOSTS.PASS;
            database = Config.MYSQL_HOSTS.DEV_NAME;
            port = Config.MYSQL_HOSTS.PORT;
            this.db = mysql.connect(host,user,password,database,port);
            callback(this.db);
    }

    //获取连续的时间
    protected static getCoherentDateArray(beginDate,endDate){
        var dateArray = [];

        beginDate = this.parseDate(beginDate);
        endDate = this.parseDate(endDate);
        while((endDate.getTime()-beginDate.getTime())>=0){
            var year = beginDate.getFullYear();
            var mon = beginDate.getMonth()+1;
            var month = mon.toString().length==1?"0"+mon.toString():mon;
            var day = beginDate.getDate().toString().length==1?"0"+beginDate.getDate():beginDate.getDate();
            dateArray.push(year+''+month+''+day);
            beginDate.setDate(beginDate.getDate()+1);
        }
        
        return dateArray;
    }

    //将数字日期字符串转成Date对象,dateString:20161228
    protected static parseDate(dateString){
        dateString = dateString.substring(0,4) + '/' + dateString.substring(4,6) + '/' + dateString.substring(6,8);
        
        return new Date(dateString);
    }

    //获取当日时间(yyyymmdd)
    protected static getNowDate(){
        var date = new Date();
        var time = date.getFullYear() + "" + (date.getMonth() < 10 ? '0' + (date.getMonth()+1) : (date.getMonth()+1))  + (date.getDate() < 10 ? '0' + date.getDate() : date.getDate());  

        return time;
    }

}
